package controller

import (
	"apitestAfterGo/common"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"apitestAfterGo/service"
	"apitestAfterGo/utils"
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/mvc"
	"time"
)

type UrlController struct {
}

func (u *UrlController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/lists/", "Lists")
	b.Handle("GET", "/findAllUrls/", "FindAllUrls")
	b.Handle("DELETE", "/removeUrl/{id:int}", "RemoveUrl")
	b.Handle("POST", "/addUrl/", "AddUrl")
	b.Handle("GET", "/getUrlDetailById/{id:int}", "GetUrlDetailById")
	b.Handle("POST", "/getAllUrlsByPage/", "GetAllUrlsByPage")
	b.Handle("PUT", "/updateUrlById/", "UpdateUrlById")
	b.Handle("POST", "/UpdateUrlByUserId/", "UpdateUrlByUserId")
	b.Handle("GET", "/getUrlsByUserId/{id:int}", "GetUrlsByUserId")
}

func (u *UrlController) Lists(context *context.Context) common.Result {
	id := utils.GetJwtParameter(context, "id")
	byId, _ := service.UserServiceImpl.GetUserById(int(id.(float64)))
	list, _ := service.ListServiceImpl.List(byId.Urls)
	return utils.Success(list, "获取当前用户菜单成功！")
}

func (u *UrlController) FindAllUrls() common.Result {
	list, _ := service.ListServiceImpl.FindAllUrls()
	return utils.Success(list, "获取所有菜单成功！")
}

func (u *UrlController) RemoveUrl(id int) common.Result {
	list, _ := service.ListServiceImpl.RemoveUrl(id)
	return utils.Success(list, "删除url成功！")
}

func (u *UrlController) AddUrl(url domain.Urls) common.Result {
	result, err := service.ListServiceImpl.AddUrl(url)
	if err != nil {
		panic(err)
	}
	return utils.Success(result, "添加url成功！")
}

func (u *UrlController) GetUrlDetailById(id int) common.Result {
	url, _ := service.ListServiceImpl.SelectTemplate(id)
	return utils.Success(url, "获取url详情成功！")
}

func (u *UrlController) GetAllUrlsByPage(dto dto.UrlInputDto) common.Result {
	count, _ := service.ListServiceImpl.GetAllUrlsCountByPage(dto)
	pages := utils.GetPages(count, dto.PageSize)
	urls, _ := service.ListServiceImpl.GetAllUrls(dto)
	page := domain.Page{
		Pages:   pages,
		Total:   count,
		Current: dto.Current,
		Size:    dto.PageSize,
		Records: urls,
	}
	return utils.Success(page, "获取所有url详情成功！")
}

func (u *UrlController) UpdateUrlById(context *context.Context, url domain.Urls) common.Result {
	username := utils.GetJwtParameter(context, "username").(string)
	url.UpdateBy = username
	url.UpdateTime = time.Now()
	result, err := service.ListServiceImpl.UpdateUrlById(url)
	if err != nil {
		panic(err)
	}
	return utils.Success(result, "更新当前url成功！")
}

func (u *UrlController) UpdateUrlByUserId(dto dto.UrlEditInputDto) common.Result {
	result, _ := service.ListServiceImpl.UpdateUrlByUserId(dto)
	return utils.Success(result, "更新当前用户url成功！")
}
func (u *UrlController) GetUrlsByUserId(id int) common.Result {
	result, _ := service.ListServiceImpl.GetUrlsByUserId(id)
	return utils.Success(result, "获取当前用户url成功！")
}
